package org.friut.util;

import java.util.ArrayList;
import java.util.List;

public class ArrayUtils {
	
	/**
	 * Array cast from object to T (specific class type)
	 * 
	 * @param array
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> arrayCast(Object[] array) {
		List<T> list = new ArrayList<T>();
		for (int i = 0; i < array.length; i++) {
			list.add((T) array[i]);
		}
		return list;
	}
	
	/**
	 * Array cast from String to Integer
	 * 
	 * @param array
	 * @return
	 */
	public static List<Integer> arrayCast(String[] array) {
		List<Integer> list = new ArrayList<Integer>();
		for (String str : array) {
			try {
				list.add(Integer.parseInt(str));
			} catch (NumberFormatException e) {
				
			}
		}
		return list;
	}
	
	/**
	 * Array contains element
	 * @param <T>
	 * 
	 * @param array
	 * @param e
	 * @return
	 */
	public static <T> boolean contains(T[] array, T e) {
		boolean flag = false;
		for (T i : array) {
			if (i.equals(e)) {
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	/**
	 * Get from array
	 * @param <T>
	 * 
	 * @param array
	 * @param idx, you must set idx = idx + 1 
	 * @return
	 */
	public static <T> T get(T[] array, int idx) {
		if (idx <= 0 || idx > array.length) {
			return array[array.length - 1];
		}
		return array[idx - 1];
	}
	
	/**
	 * Get from array
	 * @param <T>
	 * 
	 * @param array
	 * @return
	 */
	public static <T> T selectRandomElement(T[] array) {
		if (array == null || array.length == 0) {
			return null;
		}
		int r = IntegerUtils.generateRandomSeed(0, array.length - 1);
		return array[r];
	}
	
	/**
	 * Join integer array
	 * 
	 * @param a1
	 * @param a2
	 * @return
	 */
	public static int[] join(int[] a1, int[] a2) {
		int[] result = new int[a1.length + a2.length];
		System.arraycopy(a1, 0, result, 0, a1.length);
		System.arraycopy(a2, 0, result, a1.length, a2.length);
		return result;
	}
}
